//
//  SWKidEventCell.swift
//  ChildStory
//
//  Created by linhan on 2016/11/11.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit


fileprivate let ImageWidthRatio:CGFloat = 0.408


class SWKidEventCell: UITableViewCell
{
    weak var event:SWKidEvent?
    
    private var _change:Bool = true
    private var _cellWidth:CGFloat = 0
    
    private var _contentView:UIView = UIView()
    private var _titleLabel:UILabel = UILabel()
    private var _imageView:ImageLoader = ImageLoader()
    private var _countLabel:UILabel = UILabel()
    private var _featureTitleLabel:UILabel = UILabel()
    private var _summaryLabel:UILabel = UILabel()
    private var _featureContentContainer:UIView = UIView()
    private var _iconView:UIImageView = UIImageView()
    private var _newIcon:UIImageView = UIImageView(image: UIImage(named:"event_cell_icon_new"))
    
    init(style: UITableViewCellStyle, reuseIdentifier: String?, cellWidth:CGFloat)
    {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        _cellWidth = cellWidth
        setup()
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    class func getCellHeight(cellWidth:CGFloat) -> CGFloat
    {
        return cellWidth * ImageWidthRatio
    }
    
    private func setup()
    {
        selectionStyle = .none
        backgroundColor = UIColor.clear
        contentView.backgroundColor = UIColor.clear
        
        
        let contentInsets:UIEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 15)
        let ContentLeftMargin:CGFloat = 15
        let contentWidth:CGFloat = _cellWidth - contentInsets.left - contentInsets.right
        let imageWidth = _cellWidth * ImageWidthRatio
        let contentHeight:CGFloat = imageWidth
        _contentView.frame = CGRectMake(contentInsets.left, 0, contentWidth, imageWidth)
        _contentView.backgroundColor = UIColor.white
        contentView.addSubview(_contentView)
        
        let imageViewHGrid:CGFloat = 14
        _imageView.frame = CGRectMake(_contentView.width - imageWidth, 0, imageWidth, imageWidth)
        _imageView.contentMode = .scaleAspectFill
        _imageView.clipsToBounds = true
        _contentView.addSubview(_imageView)
        
        let countLabelHeight:CGFloat = 16
        _countLabel.backgroundColor = UIColor(white: 0, alpha: 0.5)
        _countLabel.textAlignment = .center
        _countLabel.font = UIFont.systemFont(ofSize: 12)
        _countLabel.frame = CGRectMake(_imageView.x, _imageView.bottom - countLabelHeight, _imageView.width, countLabelHeight)
        _contentView.addSubview(_countLabel)
        
        //类型图标
        _iconView.frame = CGRectMake(14, 15, 15, 15)
        _contentView.addSubview(_iconView)
        
        //New
        _newIcon.frame = CGRectMake(_imageView.x - imageViewHGrid - _newIcon.width, 15, _newIcon.width, _newIcon.height)
        _contentView.addSubview(_newIcon)
        
        //小标题
        let featureTitleLabelX:CGFloat = _iconView.right + 4
        _featureTitleLabel.font = UIFont.systemFont(ofSize: 12)
        _featureTitleLabel.textColor = UIColor(hex: 0xcdcdcd)
        _featureTitleLabel.frame = CGRectMake(featureTitleLabelX, 15, _newIcon.x - featureTitleLabelX, 16)
        _contentView.addSubview(_featureTitleLabel)
        
        //分割线
        let line:UIView = UIView()
        line.backgroundColor = UIColor(hex: 0xc9c9c9)
        line.frame = CGRectMake(_iconView.x, _iconView.bottom + 6, _newIcon.right - _iconView.x, 1)
        _contentView.addSubview(line)
        
        //大标题
        _titleLabel.font = UIFont.systemFont(ofSize: 17)
        _titleLabel.textColor = UIColor(hex: 0x4d4d4d)
        _titleLabel.frame = CGRectMake(ContentLeftMargin, line.bottom + 12, line.width, 21)
        _contentView.addSubview(_titleLabel)
        
        //
        let featureLabelBottomMargin:CGFloat = 12
        let featureLabelY:CGFloat = _titleLabel.bottom + 10
        let featureLabelHeight:CGFloat = contentHeight - featureLabelBottomMargin - featureLabelY
        _summaryLabel.font = UIFont.systemFont(ofSize: 12)
        _summaryLabel.textColor = UIColor(hex: 0x838383)
        _summaryLabel.numberOfLines = 0
        _summaryLabel.frame = CGRectMake(ContentLeftMargin, featureLabelY, line.width, featureLabelHeight)
        _contentView.addSubview(_summaryLabel)
    }
    
    override func prepareForReuse()
    {
        super.prepareForReuse()
        _change = true
    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        
        if let event = event , _change
        {
            let type:String = event.type ?? "1"
            var hasLocalImage:Bool = false
            _change = false
            _titleLabel.text = event.title
            _imageView.image = nil
            _iconView.image = UIImage(named:"event_cell_icon_type\(type)")
            if let eventID = event.eventID,eventID != ""
            {
                let assets = SWAssetsManager.sharedManager().assets.filter({($0.eventID ?? "") == eventID})
                _countLabel.text = "已拍\(assets.count)张"
                //显示最近拍的一张
                if let asset = assets.sorted(by: {$0.addedTime > $1.addedTime}).valueAt(0)
                {
                    var options = SWALPhotoRequestOptions()
                    options.targetSize = _imageView.frame.size.multiply(UIScreen.main.scale)
                    SWAssetsLibraryHelper.shared().fetchOriginImage(localIdentifiers: [asset.localID], options: options, completeCallback: {[weak self] results in
                        let image:UIImage? = results.valueAt(0)?.image?.retinaImage
                        self?._imageView.image = image
                    })
                    hasLocalImage = true
                }
                
            }
            
            _countLabel.isHidden = !hasLocalImage
            if !hasLocalImage
            {
                let imageURL = event.exampleImages?.flatMap({$0 as? String}).valueAt(0) ?? ""
                _imageView.load(imageURL)
            }
            
            let features:[SWKidEventFeature] = event.features?.flatMap({$0 as? SWKidEventFeature}) ?? []
            let featuresTitle:String = features.flatMap({$0.title}).joined(separator: " ")
            _featureTitleLabel.text = featuresTitle
            _summaryLabel.text = features.valueAt(0)?.content
        }
    }
    
    
    
    
}
